/**
* Script to assign annotations to stemmed text. Requires to 
* input files: one with stemmed ontology terms and one with 
* the text (one Medline Citation per line).
*/

// map to keep the ids with the stemmed concept name
def pato_id2stem = [:]
BufferedWriter bf = new BufferedWriter(new FileWriter(new File(args[2])))

// read the stemmed concept names
new File(args[0]).splitEachLine("\t") { splits ->
  if ( splits.size() > 1 ) {
    def ts = []
    ts.add(splits[1].trim().split(" "))

    if ( splits.size() > 2 ) {
      def syns = splits[2].trim().split("\\|")
      // println syns
      if (syns.size() > 0 ) syns.each { syn -> ts.add(syn.trim().split(" ")) }
    }
  
    pato_id2stem[splits[0].trim()] = ts
  }
}

// go through Medline Citations and assign MPs
new File(args[1]).splitEachLine("\t") { splits ->
  // textual data required ...
  if (splits.size() > 1) {
    def mp_id = splits[0].trim()
    def l = []

    pato_id2stem.each { p ->
      p.value.each { t ->
        def common = splits[1].trim().split(" ").grep(t)
        if ( common.size() == t.size() ) {
          l.add(new Expando(id: p.key, size: t.size()))
        }
      }
    }

    if (splits.size() > 2) {
      def spls = splits[2].trim().split("\\|")
      
      spls.each { ss ->
        if ( !ss.trim().equals("") ) {
          pato_id2stem.each { p ->
            p.value.each { t ->
              def common = ss.split(" ").grep(t)
              if ( common.size() == t.size() ) {
                l.add(new Expando(id: p.key, size: t.size()))
              }
            }
          }
        }
      }
    }

    if ( l.size() > 0 ) {
      def l_sorted = l.sort { item -> item.size}
  
      def a = l.findAll { item -> item.size == l_sorted.reverse()[0].size }
      if ( a.size() > 0 ) {
        bf << mp_id 
        a.each { bf << "\t"; bf << it.id }      
        bf << "\n"
      }
    }

  }
}

bf.flush()
bf.close()
